package com.ljsw.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ljsw.adapter.NotCompletedAdapter;
import com.ljsw.application.App;
import com.ljsw.entity.gpk.CheckInventory;
import com.ljsw.entity.gpk.NotcompeteNumState;
import com.ljsw.entity.gpk.PlateNumbers;
import com.ljsw.server.UpServer;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeoutException;

import static com.ljsw.application.App.app;

/****
 * 未完成任务实时进度
 * 需要获取时时数据 需要先调用接口6.2  查找所有标牌再  查询6.1   找到需要的未扫描标牌
 * 高红 11-4 16:29:50
 * 你需要调6.1知道已扫描的标牌，和6-2接口知道该任务需要扫的全部标牌
 * 高红 11-4 16:30:27
 * 6-1接口标牌plateNumbers为空，表示没有扫到标牌
 */
public class NotCompletedActivity extends Activity implements View.OnClickListener {
    private static final String TAG = "NotCompletedActivity";
    private TextView notcompleacuser, taskno;//  操作人,任务编号
    private Button not_completer_ql_ruku_update, black;
    private ListView listnotcomplete;
    private NotCompletedAdapter nca;
    private List<CheckInventory> PKNotCompleteList = new ArrayList<CheckInventory>();//  内层的明细结合

    private List<PlateNumbers> PlateNumberslist = new ArrayList<PlateNumbers>();// 外层集合
    private String PKNo;//  传递pk编号
    private Handler handler;
    private String userid = "";//  传递操作人
    private List<String> NotCompleLoadDataALLlist = new ArrayList<String>();//接口6.2 获取全部的数据
    private List<NotcompeteNumState> sacnlist = new ArrayList<NotcompeteNumState>(); //  获取扫描到的数据6.1
    private List<NotcompeteNumState> unscanlist = new ArrayList<NotcompeteNumState>();//  获取上面两个集合差值
    //    NotcompeteNumState//  待扫描0  已扫描1；
    private ImageView not_comple_black;
    private String Username;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_not_completed);
        PKNo = getIntent().getStringExtra("PKNO");
        Log.e(TAG, "-----" + PKNo);
        app = (App) this.getApplication();
        Username = app.user.getName();
        Log.e(TAG, "-----" + Username);
        InitView();
        taskno.setText("" + PKNo);


        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 0://   传时间获取数据成功
//                        Log.d("login用户role------------", user.getUserId());
//                        for (int x = 0; x < PKListinfolistlist.size(); x++) {
//
//                            PKListinfolistlist2.add(new PKListinfolistCode(
//                                    PKListinfolistlist.get(x).getLtOrder(),
//                                    PKListinfolistlist.get(x).getName()));
//                        }
//                        for (int i = 0; i < PKListinfolistlist2.size(); i++) {
//                            List<Integer> ltt = new ArrayList<Integer>();
//                            for (int j = 0; j < PKListinfolistlist2.get(i).getLtOrder().size(); j++) {
//                                ltt.add(1);
//                            }
//                            ltCurrent_Order.add(ltt);
//                            if (i == 0) {
//                                ltCurrent_WD.add(1);
//                            } else {
//                                ltCurrent_WD.add(0);
//                            }
//                        }


//                        wa.notifyDataSetInvalidated(); // 更新数据
                        unscanlist.clear();
                        for (int i = 0; i < NotCompleLoadDataALLlist.size(); i++) {
                            if (sacnlist.contains(NotCompleLoadDataALLlist.get(i))) {

                                Log.e(TAG, "没有数据！！！！！！！！！");
                                NotcompeteNumState notcompeteNumState = new NotcompeteNumState();
                                notcompeteNumState.setNotno(NotCompleLoadDataALLlist.get(i));
                                notcompeteNumState.setState("1");
                                unscanlist.add(notcompeteNumState);
                            } else {

                                NotcompeteNumState notcompeteNumState = new NotcompeteNumState();
                                notcompeteNumState.setNotno(NotCompleLoadDataALLlist.get(i));
                                notcompeteNumState.setState("0");
                                unscanlist.add(notcompeteNumState);//  未扫描
                            }
                        }
                        Log.e(TAG, "！！！！！！！！！" + unscanlist.size());

                        if (null == unscanlist) {//  如果当集合为null  提示没有要扫描的数据
                            handler.sendEmptyMessage(11);
                            Log.e(TAG, "没有显示的数据");

                        } else {
                            nca = new NotCompletedAdapter(unscanlist, NotCompletedActivity.this);
                            listnotcomplete.setAdapter(nca);
                            // 选中条目进行跳转
                            listnotcomplete.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                    Intent notcompletin = new Intent(NotCompletedActivity.this, NotCompletedInfoActivity.class);
                                    notcompletin.putExtra("PKNo", unscanlist.get(position).getNotno());
                                    notcompletin.putExtra("TaskNo", PKNo);
                                    startActivity(notcompletin);

                                }
                            });
                        }
                        break;
                    case 1://登录超时
                        Toast.makeText(NotCompletedActivity.this, "正在登陆请检查网络", Toast.LENGTH_SHORT).show();
                        break;
                    case 2://用户不存在
                        Toast.makeText(NotCompletedActivity.this, " 获取标牌信息失败", Toast.LENGTH_SHORT).show();
                        break;
                    case 3://异常加载，无法访问服务器
                        Toast.makeText(NotCompletedActivity.this, "请求超时", Toast.LENGTH_SHORT).show();
                        break;
                    case 4://账户长度是否正确符合要求 用户不存在
                        Toast.makeText(NotCompletedActivity.this, "账户长度不对", Toast.LENGTH_SHORT).show();
                        break;
                    case 5://判断密码的长度密码错误
                        Toast.makeText(NotCompletedActivity.this, "请检查密码", Toast.LENGTH_SHORT).show();
                        break;

                    case 7://用户不正确
                        Toast.makeText(NotCompletedActivity.this, "请检查用户名", Toast.LENGTH_SHORT).show();
                        break;
                    case 8://用户不正确
                        Toast.makeText(NotCompletedActivity.this, "无返回结果", Toast.LENGTH_SHORT).show();
                        break;
                    case 9://用户不正确
                        Toast.makeText(NotCompletedActivity.this, "任务号不正确！请返回上一层页面", Toast.LENGTH_SHORT).show();
                        break;
                    case 10://用户不正确
                        Toast.makeText(NotCompletedActivity.this, "请检查时间", Toast.LENGTH_SHORT).show();
                        break;
                    case 11://用户不正确
                        Toast.makeText(NotCompletedActivity.this, "没有待扫的标牌", Toast.LENGTH_SHORT).show();
                        break;

                    case 12:
                        nca.notifyDataSetChanged();
                        break;
                    default:
                        Toast.makeText(NotCompletedActivity.this, "请检查网络服务", Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        };
    }


    /****
     * teset
     */

    //                            Log.e(TAG, "==================" + result);
//                            JSONObject obj = JSONObject.parseObject(result);
//                            JSONArray arr = obj.getJSONArray("pageList");
//                            for (int i = 0; i < arr.size(); i++) {
//                                JSONObject jsonArray = arr.getJSONObject(i);
//
//                                String checkId = jsonArray.getString("checkId");
//                                String inventoryNumber = jsonArray.getString("inventoryNumber");
//                                mapitem.put("checkId", checkId);
//                                mapitem.put("inventoryNumber", inventoryNumber);
//                                mapitem.put("inventoryNumber", inventoryNumber);
//
//
//                            }
//                            listmapadd(mapitem);
    @Override
    protected void onResume() {
        super.onResume();
        userid = app.userZhanghao;
        NotCompleLoadDataALL();
        NotCompleLoadData();


    }

    /***
     * 获取库存内所有标牌信息
     * <p>
     * 6-2 盘查库任务点击查看库存明细
     * http://192.168.1.138:8089/cashman/webservice/ checkInventory/
     * repertoryInfo
     * ? userId=0001
     * &repertoryId=PK00001
     */
    private void NotCompleLoadDataALL() {
        new Thread(new Runnable() {
            public void run() {
                String NotCompleLoadDataALL = "";

                try {
                    NotCompleLoadDataALL = UpServer.repertoryInfo(PKNo, userid);
                    Log.e(TAG, "=========NotCompleLoadDataALL==" + NotCompleLoadDataALL);
                    NotCompleLoadDataALLlist.clear();

                    JSONObject obj = JSONObject.parseObject(NotCompleLoadDataALL);
                    JSONArray arr = obj.getJSONArray("detailList");
                    for (int i = 0; i < arr.size(); i++) {
                        JSONObject jsonArray = arr.getJSONObject(i);
                        String checkId = jsonArray.getString("SCUTCHEONSNUM");
                        NotCompleLoadDataALLlist.add(checkId);
                    }

                    handler.sendEmptyMessage(0);
                } catch (TimeoutException e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(3);
                } catch (NullPointerException e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(2);//查无此人信息
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(2);//不是数字
                } catch (Exception e) {

                    e.printStackTrace();
                    Log.e("b", "异常" + e);
//                    Log.e("data报文加密失败！", e.getMessage());
                    handler.sendEmptyMessage(2);
                }
            }
        }

        ).

                start();
    }

    /**
     * 获取数据代码
     */

    /**
     * 6.1 接口的下已扫描到的数据
     */
    private void NotCompleLoadData() {

        new Thread(new Runnable() {
            public void run() {
                String result = null;
                try {

                    if (null == PKNo || PKNo.equals("")) {
                        handler.sendEmptyMessage(9);
                    } else {

                        sacnlist.clear();
                        result = UpServer.detailInfo(PKNo, userid);
                        JSONObject obj = JSONObject.parseObject(result);
                        JSONArray arr = obj.getJSONArray("plateNumbers");
                        Log.e(TAG, "===========" + arr.size());
                        for (int i = 0; i < arr.size(); i++) {
                            JSONObject jsonArray = arr.getJSONObject(i);
                            String checkId = jsonArray.getString("SCUTCHEONSNUM");
                            NotcompeteNumState notstate = new NotcompeteNumState();
                            notstate.setNotno(checkId);
                            notstate.setState("1");
                            sacnlist.add(notstate);
                        }

                        PKNotCompleteList.clear();//  清空
//                        Gson gson = new Gson();
//                        PlateNumbers[] mTailZerotoEntity = gson.fromJson(result, PlateNumbers[].class);

//                        for (int i = 0; i < mTailZerotoEntity.length; i++) {
//                            PlateNumberslist = Arrays.asList(mTailZerotoEntity);
//                        }
                        Log.e(TAG, "===========" + PlateNumberslist.size());
                        if (PKNotCompleteList != null && !PKNotCompleteList.equals("")) {
                            handler.sendEmptyMessage(0);
                        } else {
                            handler.sendEmptyMessage(2);
                        }


                    }
                } catch (TimeoutException e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(3);
                } catch (NullPointerException e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(2);//查无此人信息
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(2);//不是数字
                } catch (Exception e) {

                    e.printStackTrace();
                    Log.e("b", "异常" + e);
//                    Log.e("data报文加密失败！", e.getMessage());
                    handler.sendEmptyMessage(2);
                }

            }
        }

        ).

                start();
    }

    private void InitView() {
        notcompleacuser = (TextView) findViewById(R.id.notcompleacuser1);
        notcompleacuser.setText(Username);
        taskno = (TextView) findViewById(R.id.taskno);

        listnotcomplete = (ListView) findViewById(R.id.listnotcomplete);

        PKNotCompleteList.clear();
        not_completer_ql_ruku_update = (Button) findViewById(R.id.not_completer_ql_ruku_update);
        not_completer_ql_ruku_update.setOnClickListener(this);
        ;
        ;
        not_comple_black = (ImageView) findViewById(R.id.not_comple_black);
        not_comple_black.setOnClickListener(this);
//        PKNotCompleteEntity PKnot = new PKNotCompleteEntity();
//        PKnot.setPKState("true 已扫描");
//        PKnot.setPKBiaopai("1 PK00001");
//        PKnot.setPKNotComInfo("   查看明细");
//        PKNotCompleteEntity PKnot2 = new PKNotCompleteEntity();
//        PKnot2.setPKState("true 已扫描");
//        PKnot2.setPKBiaopai("1 PK00001");
//        PKnot2.setPKNotComInfo("   查看明细");
//
//        PKNotCompleteList.add(PKnot);
//        PKNotCompleteList.add(PKnot2);
//
//        if (null == PKNo) {
//
//        } else {
//            taskno.setText(PKNo);
//        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.not_completer_ql_ruku_update:// 刷新6.1数据
                NotCompleLoadData();

                handler.sendEmptyMessage(12);

                break;

            case R.id.not_comple_black:
                NotCompletedActivity.this.finish();
                break;
            default:
                break;
        }

    }
}
